package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.mappers.ShenpiMapper;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.service.order.OrderService;
import com.jsh.erp.service.scorder.ScOrderService;
import com.jsh.erp.utils.*;
import jxl.Sheet;
import jxl.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author gaoqijun
 */
@RestController
@RequestMapping(value = "/order")
public class OrderController {
    private Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Resource
    private OrderService orderService;
    @Resource
    private ShenpiMapper shenpiMapper;
    @Resource
    private ScOrderService scOrderService;
    /**
     * 获取所有订单信息
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getAllList")
    public BaseResponseInfo getAllList(HttpServletRequest request)throws Exception {
        BaseResponseInfo res = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            List<Order> orderListList = orderService.getOrder();
            map.put("personList", orderListList);
            res.code = 200;
            res.data = orderListList;
        } catch(Exception e){
            e.printStackTrace();
            res.code = 500;
            res.data = "获取数据失败";
        }
        return res;
    }

    /**
     * 订单审批
     * @param ids 销售订单id
     * @param shenpiyijian 审批意见
     * @param ispass 是否通过
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/shenpi")
    public Object shenpiOrder(@RequestParam("ids") String ids,@RequestParam("shenpiyijian") String shenpiyijian,@RequestParam("ispass") String ispass,HttpServletRequest request)throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        User user = (User)request.getSession().getAttribute("user");
        int i=0;
        String[] idsArr = ids.split(",");
        for (String id :idsArr) {
            //新增审批意见
            Shenpi shenpi = new Shenpi();
            shenpi.setIspass(ispass);
            shenpi.setOrderid(id);
            shenpi.setShenheren(String.valueOf(user.getId()));
            shenpi.setShenpiyijian(shenpiyijian);
            shenpi.setSptime(StringUtil.getSysDate(""));
            i = shenpiMapper.insert(shenpi);
            if(i >= 1){
                //修改销售订单的状态
                Order order = orderService.getOrder(Long.valueOf(id));
                if("0".equals(ispass)){
                    //同意
                    order.setStatus("1");
                    //同时生成生产订单
                    ScOrder scOrder = new ScOrder();
                    scOrder.setCaizhi(order.getCaizhi());
                    scOrder.setDhrq(order.getDhrq());
                    scOrder.setGuige(order.getGuige());
                    scOrder.setKhxx(order.getKhxx());
                    scOrder.setGzdbh(order.getGzdh());
                    scOrder.setYjjhrq(order.getQwchrq());
                    scOrder.setWeight(order.getWeight());
                    scOrder.setYougou(order.getYougou());
                    scOrder.setNumber(order.getNumber());
                    scOrder.setStatus("0");
                    int j = scOrderService.insertScOrder(scOrder,request);
                    if(j <1 ){
                        logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                                ExceptionConstants.SCORDER_ADD_FAILED_CODE,ExceptionConstants.SCORDER_ADD_FAILED_MSG,ids);
                        throw new BusinessRunTimeException(ExceptionConstants.SCORDER_ADD_FAILED_CODE,
                                ExceptionConstants.SCORDER_ADD_FAILED_MSG);
                    }else{
                        int scid = scOrderService.countMax();
                        order.setGzdh(String.valueOf(scid));
                        orderService.updateOrder(order,request);
                    }
                }else{
                    //驳回
                    order.setStatus("5");
                }

            }else{
                logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                        ExceptionConstants.SHENPI_ADD_FAILED_CODE,ExceptionConstants.SHENPI_ADD_FAILED_MSG,ids);
                throw new BusinessRunTimeException(ExceptionConstants.SHENPI_ADD_FAILED_CODE,
                        ExceptionConstants.SHENPI_ADD_FAILED_MSG);
            }
        }
        return result;
    }
    /**
     * 重新申请
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/reset")
    public Object resetOrder(@RequestParam("orderid") String id,HttpServletRequest request)throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        User user = (User)request.getSession().getAttribute("user");
        int i=0;
        //修改销售订单的状态
        Order order = orderService.getOrder(Long.valueOf(id));
        order.setStatus("0");
        i = orderService.updateOrder(order,request);
        if(i < 1 ){
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.SCORDER_ADD_FAILED_CODE,ExceptionConstants.SCORDER_ADD_FAILED_MSG,id);
            throw new BusinessRunTimeException(ExceptionConstants.SCORDER_ADD_FAILED_CODE,
                    ExceptionConstants.SCORDER_ADD_FAILED_MSG);
        }
        return result;
    }
    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     *  批量删除供应商信息
     * create time: 2019/3/29 11:15
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchDeleteOrderByIds")
    public Object batchDeleteSupplierByIds(@RequestParam("ids") String ids,@RequestParam(value="deleteType",
            required =false,defaultValue= BusinessConstants.DELETE_TYPE_NORMAL)String deleteType) throws Exception {
        JSONObject result = ExceptionConstants.standardSuccess();
        int i=0;
        if(BusinessConstants.DELETE_TYPE_NORMAL.equals(deleteType)){
            i= orderService.batchDeleteByIdsNormal(ids);
        }else if(BusinessConstants.DELETE_TYPE_FORCE.equals(deleteType)){
            i= orderService.batchDeleteByIds(ids);
        }else{
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}],deleteType[{}]",
                    ExceptionConstants.DELETE_REFUSED_CODE,ExceptionConstants.DELETE_REFUSED_MSG,ids,deleteType);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_REFUSED_CODE,
                    ExceptionConstants.DELETE_REFUSED_MSG);
        }
        if(i<1){
            logger.error("异常码[{}],异常提示[{}],参数,ids[{}]",
                    ExceptionConstants.SUPPLIER_DELETE_FAILED_CODE,ExceptionConstants.SUPPLIER_DELETE_FAILED_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.SUPPLIER_DELETE_FAILED_CODE,
                    ExceptionConstants.SUPPLIER_DELETE_FAILED_MSG);
        }
        return result;
    }
    /**
     * create by: qiankunpingtai
     * website：https://qiankunpingtai.cn
     * description:
     *  批量出货
     * create time: 2020/11/23 11:15
     * @Param: ids
     * @return java.lang.Object
     */
    @RequestMapping(value = "/batchchuhuoOrderByIds")
    public String chuHuoByIds(@RequestParam("ids") String ids,@RequestParam("status") String status, HttpServletRequest result) throws Exception {
        Map<String, Object> objectMap = new HashMap<String, Object>();
        User user = (User) result.getSession().getAttribute("user");
        int update = orderService.updateStatus(ids,status,String.valueOf(user.getId()),result);
        if(update > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else if(update == -1) {
            return returnJson(objectMap, ErpInfo.TEST_USER.name, ErpInfo.TEST_USER.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }
    /**
     * 导入excel表格-客户
     * @param supplierFile
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcelCustomer")
    public void importExcelCustomer(MultipartFile supplierFile,
                                    HttpServletRequest request, HttpServletResponse response) throws Exception{
        importFun(supplierFile);
        response.sendRedirect("../pages/manage/customer.html");
    }

    /**
     * 导入excel表格-会员
     * @param orderFile
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcelMember")
    public void importExcelMember(MultipartFile orderFile,
                                  HttpServletRequest request, HttpServletResponse response) throws Exception{
        importFun(orderFile);
        response.sendRedirect("../pages/manage/order.html");
    }
    public String importFun(MultipartFile supplierFile)throws Exception{

        BaseResponseInfo info = new BaseResponseInfo();
        Map<String, Object> data = new HashMap<String, Object>();
        String message = "成功";
        try {
            Sheet src = null;
            //文件合法性校验
            try {
                Workbook workbook = Workbook.getWorkbook(supplierFile.getInputStream());
                src = workbook.getSheet(0);
            } catch (Exception e) {
                message = "导入文件不合法，请检查";
                data.put("message", message);
                info.code = 400;
                info.data = data;
            }
            //每行中数据顺序 "订单号","打标材质","刻字","客户","规格","材质","数量","工作单号","订货日期","油沟","外径","高度","孔径","出炉日期","重量（kg）","炉号"
            List<Order> sList = new ArrayList<Order>();
            for (int i = 4; i < src.getRows(); i++) {
                Order order = new Order();
                String ddNum = ExcelUtils.getContent(src, i, 0);
                if(StringUtil.isNotEmpty(ddNum)){
                    Order ddNumOrder = orderService.getOrderByDdNum(ddNum);
                    if(ddNumOrder == null){
                        order.setDdNum(ddNum);
                        order.setDbcz(ExcelUtils.getContent(src, i, 1));
                        order.setIskz(ExcelUtils.getContent(src, i, 2));
                        order.setKhxx(ExcelUtils.getContent(src, i, 3));
                        order.setGuige(ExcelUtils.getContent(src, i, 4));
                        order.setCaizhi(ExcelUtils.getContent(src, i, 5));
                        order.setNumber(ExcelUtils.getContent(src, i, 6));
                        order.setGzdh(ExcelUtils.getContent(src, i, 7));
                        order.setDhrq(ExcelUtils.getContent(src, i, 8));
                        order.setYougou(ExcelUtils.getContent(src, i, 9));
                        order.setWaijing(ExcelUtils.getContent(src, i, 10));
                        order.setHeight(ExcelUtils.getContent(src, i, 11));
                        order.setKongjing(ExcelUtils.getContent(src, i, 12));
                        order.setClrq(ExcelUtils.getContent(src, i, 13));
                        order.setWeight(ExcelUtils.getContent(src, i, 14));
                        order.setLunum(ExcelUtils.getContent(src, i, 15));
                        order.setStatus("0");
                        sList.add(order);
                    }
                }else{
                    break;
                }
            }
            info = orderService.importExcel(sList);
        } catch (Exception e) {
            e.printStackTrace();
            message = "导入失败";
            info.code = 500;
            data.put("message", message);
            info.data = data;
        }
        return null;
    }
    /**
     * 生成excel表格
     * @param beizhu
     * @param guige
     * @param khxx
     * @param beginTime
     * @param endTime
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/exportExcel")
    public void exportExcel(@RequestParam("beizhu") String beizhu,
                            @RequestParam("guige") String guige,
                            @RequestParam("khxx") String khxx,
                            @RequestParam("beginTime") String beginTime,
                            @RequestParam("endTime") String endTime,
                            @RequestParam("ddNum") String ddNum,
                            @RequestParam("type") String type,
                            @RequestParam("status") String status,
                            HttpServletRequest request, HttpServletResponse response) {
        try {
            List<OrderVoList> dataList = orderService.findByAll(khxx, beizhu, beginTime, endTime, guige,ddNum,type,status);
            String[] names = {"订单号","打标材质","刻字","客户","规格","材质","数量","工作单号","订货日期","油沟","外径","高度","孔径","出炉日期","重量（kg）","炉号"};
            String title = "登记订单";
            List<String[]> objects = new ArrayList<String[]>();
            if (null != dataList) {
                for (OrderVoList order : dataList) {
                    String[] objs = new String[15];
                    objs[0] = order.getDdNum();
                    objs[1] = order.getDbcz();
                    objs[2] = order.getIskz();
                    objs[3] = order.getKhxx();
                    objs[4] = order.getGuige();
                    objs[5] = order.getCaizhi();
                    objs[6] = order.getNumber();
                    objs[7] = order.getGzdh();
                    objs[8] = order.getDhrq();
                    objs[9] = order.getYougou();
                    objs[10] = order.getWaijing();
                    objs[11] = order.getHeight();
                    objs[12] = order.getKongjing();
                    objs[13] = order.getClrq();
                    objs[14] = order.getLunum();
                    objects.add(objs);
                }
            }
            File file = ExcelUtils.exportObjectsWithoutTitle(title, names, title, objects);
            ExportExecUtil.showExec(file, file.getName(), response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
